package com.skyolder.milkbee.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Advertisement;
import com.skyolder.milkbee.service.AdvertisementService;
import com.skyolder.milkbee.tool.FileUtil;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;

import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Advertisement.
 */
@RestController
@RequestMapping("/api")
public class AdvertisementResource {

	private final Logger log = LoggerFactory.getLogger(AdvertisementResource.class);

	@Inject
	private AdvertisementService advertisementService;

	/**
	 * POST /advertisements : Create a new advertisement.
	 *
	 * @param advertisement
	 *            the advertisement to create
	 * @return the ResponseEntity with status 201 (Created) and with body the
	 *         new advertisement, or with status 400 (Bad Request) if the
	 *         advertisement has already an ID
	 * @throws URISyntaxException
	 *             if the Location URI syntax is incorrect
	 */
	@PostMapping("/advertisements")
	@Timed
	public ResponseEntity<Advertisement> createAdvertisement(@RequestBody Advertisement advertisement,
			HttpServletRequest request) throws URISyntaxException {
		log.debug("REST request to save Advertisement : {}", advertisement);
		if (advertisement.getId() != null) {
			return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("advertisement", "idexists",
					"A new advertisement cannot already have an ID")).body(null);
		}
		advertisement.setCreatedAt(ZonedDateTime.now());

		Advertisement result = advertisementService.save(advertisement);
		String realpath = request.getSession().getServletContext().getRealPath(FileUploader.GIFT);
		String oldpath = realpath + "/" + result.getImage();
		String newpath = realpath + "/" + result.getId() + ".jpg";
		boolean b = FileUtil.renameFile(oldpath, newpath);
		if (b) {
			result.setImage(result.getId() + ".jpg");
		}
		advertisementService.save(result);
		return ResponseEntity.created(new URI("/api/advertisements/" + result.getId()))
				.headers(HeaderUtil.createEntityCreationAlert("advertisement", result.getId().toString())).body(result);
	}

	/**
	 * PUT /advertisements : Updates an existing advertisement.
	 *
	 * @param advertisement
	 *            the advertisement to update
	 * @return the ResponseEntity with status 200 (OK) and with body the updated
	 *         advertisement, or with status 400 (Bad Request) if the
	 *         advertisement is not valid, or with status 500 (Internal Server
	 *         Error) if the advertisement couldnt be updated
	 * @throws URISyntaxException
	 *             if the Location URI syntax is incorrect
	 */
	@PutMapping("/advertisements")
	@Timed
	public ResponseEntity<Advertisement> updateAdvertisement(@RequestBody Advertisement advertisement,
			HttpServletRequest request) throws URISyntaxException {
		log.debug("REST request to update Advertisement : {}", advertisement);
		if (advertisement.getId() == null) {
			return createAdvertisement(advertisement, request);
		}
		Advertisement result = advertisementService.save(advertisement);
		return ResponseEntity.ok()
				.headers(HeaderUtil.createEntityUpdateAlert("advertisement", advertisement.getId().toString()))
				.body(result);
	}

	/**
	 * GET /advertisements : get all the advertisements.
	 *
	 * @param pageable
	 *            the pagination information
	 * @return the ResponseEntity with status 200 (OK) and the list of
	 *         advertisements in body
	 * @throws URISyntaxException
	 *             if there is an error to generate the pagination HTTP headers
	 */
	@GetMapping("/advertisements")
	@Timed
	public ResponseEntity<List<Advertisement>> getAllAdvertisements(@ApiParam(required = false) Integer stat,
			@ApiParam Pageable pageable) throws URISyntaxException {
		log.debug("REST request to get a page of Advertisements");
		if (stat == null) {
			stat = 1;
		}
		Page<Advertisement> page =null;
		switch (stat) {
		case 1: {
			page = advertisementService.queryByPrematurity(pageable);
		}
			break;
		case 2: {
			page = advertisementService.queryByOnline(pageable);
		}
			break;
		case 3: {
			page = advertisementService.queryByExpire(pageable);
		}
			break;
		default: {
			page = advertisementService.findAll(pageable);
		}
		}
		 
		HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/advertisements");
		return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
	}

	/**
	 * GET /advertisements/:id : get the "id" advertisement.
	 *
	 * @param id
	 *            the id of the advertisement to retrieve
	 * @return the ResponseEntity with status 200 (OK) and with body the
	 *         advertisement, or with status 404 (Not Found)
	 */
	@GetMapping("/advertisements/{id}")
	@Timed
	public ResponseEntity<Advertisement> getAdvertisement(@PathVariable Long id) {
		log.debug("REST request to get Advertisement : {}", id);
		Advertisement advertisement = advertisementService.findOne(id);
		return Optional.ofNullable(advertisement).map(result -> new ResponseEntity<>(result, HttpStatus.OK))
				.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
	}

	/**
	 * DELETE /advertisements/:id : delete the "id" advertisement.
	 *
	 * @param id
	 *            the id of the advertisement to delete
	 * @return the ResponseEntity with status 200 (OK)
	 */
	@DeleteMapping("/advertisements/{id}")
	@Timed
	public ResponseEntity<Void> deleteAdvertisement(@PathVariable Long id) {
		log.debug("REST request to delete Advertisement : {}", id);
		advertisementService.delete(id);
		return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("advertisement", id.toString()))
				.build();
	}

}
